package tlias.Interceptor;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import tlias.utils.CurrentHolder;
import tlias.utils.JwtUtils;

@Slf4j
@Component
public class TokenInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
      log.info("preHandle");
        String uri = request.getRequestURI();
        if(uri.contains("/login")){
            log.info("login");
            return true;
        }
        if (request.getHeader("token")==null || request.getHeader("token").isEmpty()){
            response.setStatus(401);
            response.getWriter().write("token is null");
            log.info("token is null");
            return false;
        }
        try {
            JwtUtils.verifyJwt(request.getHeader("token"));
            log.info("token is valid");
            CurrentHolder.setCurrentId(JwtUtils.getIdByJwt(request.getHeader("token")));
            return true;
        } catch (Exception e) {
            response.setStatus(401);
            response.getWriter().write("token is invalid");
            log.info("token is invalid");
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        log.info("postHandle");
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        log.info("afterCompletion");
    }
}
